<?php
/**
 *  切片任务
 */
class clip_task_model{
	const TASK_C_STATE_ADD = 'add';
	const TASK_C_STATE_HANDLE = 'handle';
	const TASK_C_STATE_WAIT = 'wait';
	const TASK_C_STATE_OK = 'ok';
	const TASK_C_STATE_GET_MEDIA_URL_SUCC = 'get_media_url_succ';
	const TASK_C_STATE_GET_MEDIA_URL_FAIL = 'get_media_url_fail';
	const TASK_C_STATE_DOWNLOAD = 'download';
	const TASK_C_STATE_DOWNLOAD_SUCC = 'download_succ';
	const TASK_C_STATE_DOWNLOAD_FAIL = 'download_fail';
	const TASK_C_STATE_CLIPING = 'cutting';
	const TASK_C_STATE_CLIP_SUCC = 'clip_succ';
	const TASK_C_STATE_CLIP_FAIL = 'clip_fail';
	const TASK_C_STATE_CANCEL = 'cancel';
	const TASK_C_STATE_FAIL = 'fail';
	const TASK_C_STATE_C2_HANDLE = 'c2_handle';
	const TASK_C_STATE_C2_SUCC = 'c2_ok';
	const TASK_C_STATE_C2_FAIL = 'c2_fail';
	const TASK_C_STATE_C2_DELETE_HANDLE = 'c2_delete_handle';
	const TASK_C_STATE_C2_DELETE_SUCC = 'c2_delete_ok';
	const TASK_C_STATE_C2_DELETE_FAIL = 'c2_delete_fail';
	//DRM
	const TASK_C_STATE_DRM_SUCC = 'drm_ok';
	const TASK_C_STATE_DRM_FAIL = 'drm_fail';
	const TASK_C_STATE_GET_DRM_KEY_SUCC = 'get_drm_key_succ';
	const TASK_C_STATE_GET_DRM_KEY_FAIL = 'get_drm_key_fail';
	//clip  drm
	const TASK_C_STATE_CLIP_DRM_SUCC = 'drm_encrypt_ok';
	const TASK_C_STATE_CLIP_DRM_FAIL = 'drm_encrypt_fail';
	const TASK_C_STATE_CLIP_DRM_LOADING = 'drm_encrypt_loading';
	
	//clip  转码 encode
	const TASK_C_STATE_CLIP_ENCODE_SUCC = 'clip_encode_ok';
	const TASK_C_STATE_CLIP_ENCODE_FAIL = 'clip_encode_fail';
	const TASK_C_STATE_CLIP_ENCODE_LOADING = 'clip_encode_loading';
	const TASK_C_STATE_CLIP_ENCODE_WAIT = 'clip_encode_wait';

	//clip 上传 upload
    const TASK_C_STATE_CLIP_UPLOADING = 'uploading';
    const TASK_C_STATE_CLIP_UPLOAD_SUC = 'upload_suc';
    const TASK_C_STATE_CLIP_UPLOAD_FAIL = 'upload_fail';
	

	//clip  直播转点播 encode
	const TASK_C_STATE_LIVE_TO_MEDIA_FAIL = 'live_to_media_fail';
	const TASK_C_STATE_LIVE_TO_MEDIA_LOADING = 'live_to_media_loading';
	const TASK_C_STATE_LIVE_TO_MEDIA_WAIT = 'live_to_media_wait';
	
	
	static $task_state_arr = array(
	self::TASK_C_STATE_ADD	=>'添加任务',//执行成功
	self::TASK_C_STATE_HANDLE =>'任务已下发',//任务已下发（被切片工具取走）
	self::TASK_C_STATE_WAIT	=>'等待下发',//执行成功
	self::TASK_C_STATE_OK	 =>'上报成功',//执行成功
	self::TASK_C_STATE_GET_MEDIA_URL_SUCC	 =>'取片源下载地址成功',
	self::TASK_C_STATE_GET_MEDIA_URL_FAIL	 =>'取片源下载地址失败',
	self::TASK_C_STATE_DOWNLOAD	 =>'下载影片',//下载影片
	self::TASK_C_STATE_DOWNLOAD_SUCC	 =>'下载成功',//下载影片
	self::TASK_C_STATE_DOWNLOAD_FAIL	 =>'下载失败',//下载影片
	self::TASK_C_STATE_CLIPING	  =>'正在切片',//正在切片
	self::TASK_C_STATE_CLIP_SUCC	  =>'切片成功',
	self::TASK_C_STATE_CLIP_FAIL	  =>'切片失败',
	self::TASK_C_STATE_CANCEL	   =>'任务已取消',//任务取消
	self::TASK_C_STATE_FAIL		 =>'切片失败',//切片失败
	self::TASK_C_STATE_C2_HANDLE		 =>'执行注入',//
	self::TASK_C_STATE_C2_SUCC		 =>'注入成功',
	self::TASK_C_STATE_C2_FAIL		 =>'注入失败',
	self::TASK_C_STATE_C2_DELETE_HANDLE		 =>'等待删除已注入片源',
	self::TASK_C_STATE_C2_DELETE_SUCC		 =>'删除已注入片源成功',
	self::TASK_C_STATE_C2_DELETE_FAIL		 =>'删除已注入片源失败',
	self::TASK_C_STATE_DRM_SUCC		 =>'注入DRM成功',
	self::TASK_C_STATE_DRM_FAIL		 =>'注入DRM失败',
	self::TASK_C_STATE_GET_DRM_KEY_SUCC =>'获取DRM密钥成功',
	self::TASK_C_STATE_GET_DRM_KEY_FAIL =>'获取DRM密钥失败',

	self::TASK_C_STATE_CLIP_DRM_SUCC        =>'DRM加密成功',
	self::TASK_C_STATE_CLIP_DRM_FAIL 		=>'DRM加密失败',
	self::TASK_C_STATE_CLIP_DRM_LOADING 	=>'正在DRM加密',

    self::TASK_C_STATE_CLIP_UPLOADING        =>'上传中',
    self::TASK_C_STATE_CLIP_UPLOAD_SUC 		=>'上传成功',
    self::TASK_C_STATE_CLIP_UPLOAD_FAIL 	=>'上传失败',

    self::TASK_C_STATE_CLIP_ENCODE_SUCC        =>'文件转码成功',
    self::TASK_C_STATE_CLIP_ENCODE_FAIL 	   =>'文件转码失败',
    self::TASK_C_STATE_CLIP_ENCODE_LOADING 	   =>'正在文件转码',
	self::TASK_C_STATE_CLIP_ENCODE_WAIT 	   =>'等待文件转码',
	    

	    self::TASK_C_STATE_LIVE_TO_MEDIA_FAIL 	   =>'直播转点播失败',
	    self::TASK_C_STATE_LIVE_TO_MEDIA_LOADING 	   =>'正在直播转点播',
	    self::TASK_C_STATE_LIVE_TO_MEDIA_WAIT 	   =>'等待直播转点播',
	);
	static $task_type_default = 'std';
	/**
	 * 码流对应序号表
	 */
	static $mode_index = array(
	'std'=>'01',
	'hd'=>'02',
	'low'=>'03',
	'4k'=>'04',
	);
	static public function get_kbps_index($mode){
		$mode= strtolower($mode);
		$mode_index = '01';
		if($mode && isset(self::$mode_index[$mode])){
			$mode_index = clip_task_model::$mode_index[$mode];
		}
		return $mode_index;
	}
	
	/**
	 * 获取片源的hash值
	 * @param string $media_import_id
	 * @return string
	 * @author liangpan
	 * @date 2015-09-10
	 */
	static public function get_media_hash($media_import_id,$nns_cp_id=null)
	{
		$media_hash='';
		if(empty($media_import_id))
		{
			return $media_hash;
		}
		$nns_cp_id = (strlen($nns_cp_id) > 0) ? $nns_cp_id : 0;
		$db = nn_get_db(NL_DB_READ);
		$sql="select * from nns_vod_media_ex where nns_vod_media_id='{$media_import_id}' and nns_key='file_hash' and nns_cp_id='{$nns_cp_id}' limit 1";
		$result = nl_query_by_db($sql, $db);
		if(!$result || !is_array($result) || !isset($result[0]['nns_value']))
		{
			return $media_hash;
		}
		return $result[0]['nns_value'];
	}
	/**
	 * 添加任务
	 * 如果同一分集存在未处理的任务，则将其取消
	 * 如果是手动重发任务，则把优先级权重置为最高
	 * @param $task_info array(
	 * 'nns_task_type',
	 * 'nns_org_id',
	 * 'nns_video_id',
	 * 'nns_video_index_id',
	 * 'nns_index',//第几集
	 * 'nns_create_time',
	 * 'nns_force'  是否强制切片1：是 0：否
	 * )
	 */
	static public function add_task($task_info,$dc=null)
	{
	    if($dc === null)
	    {
	        $dc = nl_get_dc(array (
	            'db_policy' => NL_DB_WRITE,
	            'cache_policy' => NP_KV_CACHE_TYPE_MEMCACHE
	        ));
	    }
	    $db_w  = $db = $dc->db();
		$_params = array(
		'nns_vod_id'=>$task_info['nns_video_id'],
		'nns_vod_index_id'=>$task_info['nns_video_index_id']
		);
		if($task_info['nns_video_type'] == 2)
		{
		    $b_media_exists = self::_file_package_exists($task_info,$dc);
		}
		else if($task_info['nns_video_type'] == 1)
		{
		    $b_media_exists = self::_live_media_exists($task_info,$dc);
		}
		else
		{
		    $task_info['nns_video_type'] = 0;
		    $b_media_exists = self::_vod_media_exists_v2($task_info,$db_w);
		}
		
				
		if(!isset($b_media_exists[0]) || !is_array($b_media_exists[0]) || empty($b_media_exists[0])){
			//该分集下还没有片源，不添加任务
			DEBUG && i_write_log_core('分集下还没有片源，不添加任务'.var_export($task_info,true));
			return false;
		}
		$b_media_exists = $b_media_exists[0];
		
		$cp_config = nl_cp::query_by_id($dc, $b_media_exists['nns_cp_id']);
		$cp_config = (isset($cp_config['data_info']['nns_config']) && strlen($cp_config['data_info']['nns_config']) >0) ? json_decode($cp_config['data_info']['nns_config'],true) : null;
		
		
		
		$cancel = self::$task_state_arr['cancel'];
		//添加任务之前取消之前的任务
		$sql = "select * from nns_mgtvbk_clip_task where nns_org_id='".$task_info['nns_org_id']."' and   nns_video_type='".$task_info['nns_video_type']."' and nns_video_id='".$task_info['nns_video_id']."' and nns_video_index_id='".$task_info['nns_video_index_id']."' and nns_video_media_id='".$task_info['nns_video_media_id']."'  and nns_state!='".self::TASK_C_STATE_CANCEL."'";
		$result = nl_db_get_all($sql,$db);
		if($result!=false && is_array($result)){
			foreach($result as $task_item){			
				$sql = "update nns_mgtvbk_clip_task set  nns_state='".self::TASK_C_STATE_CANCEL."',nns_desc='".self::$task_state_arr[self::TASK_C_STATE_CANCEL]."'  where nns_id='".$task_item['nns_id']."'";
				nl_execute_by_db($sql,$db_w);
				$task_log = array(
				'nns_task_id' => $task_item['nns_id'],
				'nns_state'   => self::TASK_C_STATE_CANCEL,
				'nns_desc'	=> self::$task_state_arr[clip_task_model::TASK_C_STATE_CANCEL],
				'nns_video_id'=>$task_info['nns_video_id'],
				'nns_video_index_id'=>$task_info['nns_video_index_id']
				);	
				self::add_task_log($task_log);
			}
			
		}
		//马上添加新的任务
		if(empty($task_info['nns_task_type'])){
			$task_info['nns_task_type'] = self::$task_type_default;
		}

		$task_info['nns_create_time'] = date('Y-m-d H:i:s');
		$task_info['nns_priority'] = isset($task_info['nns_priority']) ? (int)$task_info['nns_priority'] : 0;
		unset($task_info['nns_index']);

		$task_info['nns_id'] = np_guid_rand();
		//添加内容到DRM
		$sp_config = sp_model::get_sp_config($task_info['nns_org_id']);
		//$drm_enabled = get_drm_config("g_drm_enable");
// 		//查询DRM 是否关闭
// 		if((isset($sp_config['main_drm_enabled']) && intval($sp_config['main_drm_enabled']) == 1) && (isset($sp_config['q_disabled_drm']) && intval($sp_config['q_disabled_drm']) == 1) && $drm_enabled == 1)
		if(isset($sp_config['main_drm_enabled']) && intval($sp_config['main_drm_enabled']) == 1 && $task_info['nns_video_type'] == 0)
		{
			//检查是否属于重切
			if($result != false && is_array($result))
			{
				DEBUG && i_write_log_core('重切片源，不需要注入DRM'.var_export($result,true));
			}
			else 
			{
				$drm_params = array(
					'nns_media_id' => $b_media_exists['nns_import_id'],
					'nns_description' => 'IMPORT_MEDIA'
				);
				$drm_result = nl_m_media::add_media($db_w, $drm_params);
				DEBUG && i_write_log_core('DRM注入:' . var_export($drm_result,true),$task_info['nns_org_id']);
				if($drm_result['code'] != 'ML_STATE_OK')
				{
					$task_log = array(
						'nns_task_id' => $task_item['nns_id'],
						'nns_state'   => self::TASK_C_STATE_DRM_FAIL,
						'nns_desc'	=> self::$task_state_arr[clip_task_model::TASK_C_STATE_DRM_FAIL],
						'nns_video_id'=>$task_info['nns_video_id'],
						'nns_video_index_id'=>$task_info['nns_video_index_id']
					);	
					self::add_task_log($task_log);
					return false;
				}
			}
		}
		if(isset($cp_config['cp_playbill_to_media_enabled']) && $cp_config['cp_playbill_to_media_enabled'] == '1' && isset($cp_config['source_notify_url']) && strlen($cp_config['source_notify_url']) >0)
		{
		    $task_info['nns_state'] = self::TASK_C_STATE_LIVE_TO_MEDIA_WAIT;
		    
		    $task_log = array(
		        'nns_task_id'=>$task_info['nns_id'],
		        'nns_state' => self::TASK_C_STATE_LIVE_TO_MEDIA_WAIT,
		        'nns_desc'  => self::$task_state_arr[self::TASK_C_STATE_LIVE_TO_MEDIA_WAIT],
		    );
		    self::add_task_log($task_log);
		}
		
		
		$result = nl_db_insert($db_w,'nns_mgtvbk_clip_task',$task_info);
		if($result == false){
		   	DEBUG && i_write_log_core('任务添加,数据库执行失败',$task_info['nns_org_id']);
		   	return false;
		}
		$task_log = array(
			'nns_task_id'=>$task_info['nns_id'],
			'nns_state' => self::TASK_C_STATE_ADD,
			'nns_desc'  => self::$task_state_arr[self::TASK_C_STATE_ADD],
		);
		self::add_task_log($task_log);
		DEBUG && i_write_log_core('添加任务成功',$task_info['nns_org_id']);
		return true;
	}
	static public function _vod_media_exists($params){
		$sql = "select * from nns_vod_media where nns_id='{$params['nns_video_media_id']}' and  nns_deleted != 1 and  nns_vod_id='{$params['nns_video_id']}' and nns_vod_index_id='{$params['nns_video_index_id']}'";
		$db = nn_get_db(NL_DB_READ);
	//echo $sql;
		$result = nl_query_by_db($sql,$db);	
		if($result===true) return false;
		return true;
	}
	
	static public function _live_media_exists($params){
	    $sql = "select * from nns_live_media where nns_id='{$params['nns_video_media_id']}' and  nns_deleted != 1 and  nns_vod_id='{$params['nns_video_id']}' and nns_vod_index_id='{$params['nns_video_index_id']}'";
	    $db = nn_get_db(NL_DB_READ);
	    //echo $sql;
	    $result = nl_query_by_db($sql,$db);
	    return $result;
	}
	
	static public function _file_package_exists($params){
	    $sql = "select * from nns_file_package where nns_id='{$params['nns_video_id']}' and  nns_deleted != 1 ";
	    $db = nn_get_db(NL_DB_READ);
	    //echo $sql;
	    $result = nl_query_by_db($sql,$db);
	    return $result;
	}
	
	static public function _vod_media_exists_v2($params,$db)
	{
	    $sql = "select * from nns_vod_media where nns_id='{$params['nns_video_media_id']}' and  nns_deleted != 1 and  nns_vod_id='{$params['nns_video_id']}' and nns_vod_index_id='{$params['nns_video_index_id']}'";
	    return  nl_query_by_db($sql,$db);
	}
	
	static public function _get_vod_media($params){
		$sql = "select * from nns_vod_media where nns_id='{$params['nns_video_media_id']}' and  nns_deleted != 1 and  nns_vod_id='{$params['nns_video_id']}' and nns_vod_index_id='{$params['nns_video_index_id']}'";
		$db = nn_get_db(NL_DB_READ);
	//echo $sql;
		$result = nl_db_get_one($sql,$db);	
		nn_close_db($db);
		if(is_array($result)) return $result;
		return false;
	}
	/**
	 * 切片队列任务重发
	 */
	static public function restart_task($task_id,$force=false)
    {
		$task_info = self::get_task_by_id($task_id);
		$task_info['nns_force']= $force?'1':'0';
		unset($task_info['nns_state']);
		unset($task_info['nns_content']);
		unset($task_info['nns_desc']);
		unset($task_info['nns_alive_time']);
		unset($task_info['nns_start_time']);
		unset($task_info['nns_end_time']);
		unset($task_info['nns_modify_time']);
		unset($task_info['nns_file_hit']);
		
		$op_id = $task_info['nns_op_id'];
		if($op_id)
		{
			$db = nn_get_db(NL_DB_WRITE);
			$sql_queue = "select nns_id from nns_mgtvbk_op_queue where nns_id='{$op_id}'";
			$info = nl_db_get_one($sql_queue, $db);
			if(empty($info))
			{
				nl_execute_by_db("update nns_mgtvbk_clip_task set nns_state='cancel' where nns_id='{$task_id}'", $db);
				RETURN TRUE;
			}

			//查询这个切片里面的媒体是不是删除
			$sp_id = $task_info['nns_org_id'];
			$nns_vod_index_id = $task_info['nns_video_index_id'];
			$nns_vod_media_id = $task_info['nns_video_media_id'];
			$sql = "select * from nns_mgtvbk_c2_task where nns_org_id='{$sp_id}' and nns_type='media' and nns_ref_id='$nns_vod_media_id' and nns_src_id='$nns_vod_index_id'";
			$c2_info = nl_db_get_one($sql, $db);
			if(is_array($c2_info) && $c2_info != null)
			{
				if($c2_info['nns_action'] == 'destroy')
				{
					nl_execute_by_db("update nns_mgtvbk_clip_task set nns_state='cancel' where nns_id='{$task_id}'", $db);
					RETURN TRUE;
				}
			}
            if(isset($task_info['nns_cp_id']) && empty($task_info['nns_cp_id']))
            {
                $task_info['nns_cp_id'] = $info['nns_cp_id'];
            }
		}
		$add_task = self::add_task($task_info);
		return $add_task;
	}
	static public function add_task_by_vod_id($vod_id){
		DEBUG && i_write_log_core('mgtv注入完成，开始添加任务...');
		$db = nn_get_db(NL_DB_READ);
		
		$sql = "select * from nns_vod_index where nns_deleted != 1 and  nns_vod_id='$vod_id'";
		$indexes = nl_db_get_all($sql,$db);
		if(is_array($indexes) && count($indexes)>0){
			foreach($indexes as $index_info){
				$task_info['nns_video_id'] = $index_info['nns_vod_id'];
				$task_info['nns_video_type'] = 0;
				$task_info['nns_video_index_id'] = $index_info['nns_id'];
				$task_info['nns_index'] = $index_info['nns_index'];
				self::add_task($task_info);
				
			}
		}else{
			DEBUG && i_write_log_core('影片下可能没有分集，或者数据库执行失败...');
		}
	}
	/**
	 * 有新片源的分集加入切片任务中
	 */
	static public function add_task_by_new_media(){
		$db = nn_get_db(NL_DB_READ);
				
		//条件：有新片源，并且分分片信息已经注入,并且MEDIA_TIME_OUT 秒 没有片源更新;每次限制跑30条
		//$sql = "select i.* from nns_vod_index i join nns_mgtvbk_c2_task ct on ct.nns_ref_id=i.nns_id where (i.nns_new_media='1' && i.nns_new_media_time < NOW() - INTERVAL ".MEDIA_TIME_OUT." SECOND  or i.nns_new_media='' or ISNULL(i.nns_new_media) ) && ct.nns_type='index' && ct.nns_status=0 ";
		$sql = "select * from nns_vod_index where nns_deleted != 1 and  (nns_new_media='1' && nns_new_media_time < NOW() - INTERVAL ".MEDIA_TIME_OUT." SECOND  or nns_new_media='' or ISNULL(nns_new_media)) limit 30";
		$indexes = nl_db_get_all($sql,$db);
		if(is_array($indexes) && count($indexes)>0){
			foreach($indexes as $index_info){
				$task_info['nns_video_type'] = 0;
				$task_info['nns_video_id'] = $index_info['nns_vod_id'];
				$task_info['nns_video_index_id'] = $index_info['nns_id'];
				$task_info['nns_index'] = $index_info['nns_index'];
				self::add_task($task_info);

			}
		}else{
			DEBUG && i_write_log_core('没有有新片源的分集');
		}		
	}
	static public function test_add_task_by_new_media(){
		DEBUG && i_write_log_core('--测试添加切片任务---');
		$db = nn_get_db(NL_DB_READ);
			
		//条件：有新片源，并且分分片信息已经注入,并且MEDIA_TIME_OUT 秒 没有片源更新;每次限制跑200条
		$sql = "select * from nns_vod_index  ";
		$indexes = nl_db_get_all($sql,$db);
		if(is_array($indexes) && count($indexes)>0){
			DEBUG && i_write_log_core('共添加分集:'.count($indexes));
			foreach($indexes as $index_info){
				$task_info['nns_video_type'] = 0;
				$task_info['nns_video_id'] = $index_info['nns_vod_id'];
				$task_info['nns_video_index_id'] = $index_info['nns_id'];
				$task_info['nns_index'] = $index_info['nns_index'];
				self::add_task($task_info);

			}
		}else{
			DEBUG && i_write_log_core('没有有新片源的分集');
		}		
	}
	/**
	 * 有新片源
	 */
	static public function update_new_media_state($vod){
		//i_write_log_core('影片('.$vod['vod_id'].')分集('.$vod['vod_index_id'].')-------有新片源---');
		$db = nn_get_db(NL_DB_WRITE);
	
		$str_sql = "update nns_vod_index set nns_new_media='{$vod['status']}',nns_new_media_time=now() where nns_id='{$vod['vod_index_id']}' and nns_vod_id='{$vod['vod_id']}' ";
		return nl_execute_by_db($str_sql,$db);
	}
	
	/**
	 * $param array('nns_video_id','nns_video_type','nns_video_index_id')
	 */
	static public function _build_task_content($param,$clip_flag_enabled=0,$cp_config=null)
	{
		$db = nn_get_db(NL_DB_READ);
		$db_w = nn_get_db(NL_DB_WRITE);
		$video_info = null;	
		$video_index_info = null;	
		$media_list = null;
		$video_info_type='video';
		$index_info_type='index';
		$imedia_info_type='media';
		if($param['nns_video_type']==0){
			//vod
			$vod_id = $param['nns_video_id'];
			$sql = "select * from nns_vod where nns_id='".$vod_id."'";
			$video_info = nl_db_get_one($sql,$db);
			$sql = "select * from nns_vod_index where nns_id='".$param['nns_video_index_id']."'";
			$video_index_info = nl_db_get_one($sql,$db);
			$media_list = self::get_vod_media($param);
		}else{
			//live
			$live_id = $param['nns_video_id'];
			$sql = "select * from nns_live where nns_id='".$live_id."'";
			$video_info = nl_db_get_one($sql,$db);
			$sql = "select * from nns_live_index where nns_id='".$param['nns_video_index_id']."'";
			$video_index_info = nl_db_get_one($sql,$db);
			$media_list = self::get_live_media($param);
			$video_info_type='live';
			$index_info_type='live_index';
			$imedia_info_type='live_media';
		}
		$sp_config = sp_model::get_sp_config($param['nns_org_id']);
		include_once dirname(dirname(__FILE__)).'/'.$param['nns_org_id'].'/define.php';
		$str_media_download_url  = (isset($sp_config['down_url']) && !empty($sp_config['down_url'])) ? $sp_config['down_url'] : '';
		if(strlen($str_media_download_url) <1)
		{
		    return false;
		}
		
		$str_live_to_media=0;
		if($param['nns_video_type']==0 && $media_list[0]['nns_live_to_media'] == '1')
		{
		    $str_live_to_media=1;
		}
        $up_ftp = '';
        if(isset($sp_config['upload_clip_to_ftp_enabled']) && $sp_config['upload_clip_to_ftp_enabled'] == '1')
        {
            $up_ftp = rtrim($sp_config['upload_clip_to_ftp_url'],"/");
            if(isset($sp_config['upload_clip_to_ftp_dir_mode']))
            {
                switch ($sp_config['upload_clip_to_ftp_dir_mode'])
                {
                    case '1': //山东有线上传到指定目录  producer+YYYYMM / nns_ext_url //针对单片源时使用
                        $vod_producer = strtoupper($video_info['nns_producer']);
                        $vod_producer_len = strlen($vod_producer);
                        $up_ftp .= "/$vod_producer" . substr(ltrim($media_list[0]['nns_ext_url']),$vod_producer_len,6) . "/" . ltrim($media_list[0]['nns_ext_url']);
                        break;
                }
            }
        }

		$force = !empty($param['nns_force'])?'1':'0';
		$ret_xml = '';
		$ret_xml .=	'<task id="'.$param['nns_id'].'" force="'.$force.'" model="0" type="'.$str_live_to_media.'" file_save_mode="'.$sp_config['upload_clip_to_ftp_enabled'].'" ftp_addr="'.$up_ftp.'">';
		if((int)$sp_config['import_id_mode'] !== 1 && (int)$sp_config['import_id_mode'] !== 3)
		{
			$result_video_data = public_model_exec::get_asset_id_by_sp_id($param['nns_org_id'], $video_info_type, $param['nns_video_id'],$video_info,$sp_config);
			$param['nns_video_id'] = $str_media_temp_id = (isset($result_video_data['data_info']) && strlen($result_video_data['data_info']) >0) ? $result_video_data['data_info'] : $param['nns_video_id'];
		}
		else 
		{
			$str_media_temp_id = $param['nns_video_id'];
		}
		$ret_xml .= '<video id="'.$param['nns_video_id'].'" name="'.htmlspecialchars($video_info['nns_name'], ENT_QUOTES).'" video_type="'.$param['nns_video_type'].'" pinyin="'.$video_info['nns_pinyin'].'">';
		$ret_xml .=	'<index_list>';
		$i = 0;
		$flag_media_type = 'ts';
		$media_xml = '<media_list>';
		foreach($media_list as $media_info)
		{
		    $url = $str_media_download_url.'file_id='.$media_info['nns_import_id'].'&cp_id='.$media_info['nns_cp_id'];
			$result = file_get_contents($url);
			$ret_arr = json_decode($result, true);
			if($ret_arr['err']=='1'){
				
				$task_log = array(
				'nns_task_id' => $param['nns_id'],
				'nns_state'   => 'get_media_url_fail',
				'nns_desc'	=> $url.'======='.$result,
				);	
				self::add_task_log($task_log);	
				continue;
			}
			if(empty($media_info['nns_name']))
			{
				$media_info['nns_name'] = $video_info['nns_name'].$video_index_info['nns_index'].$media_info['nns_mode'];
			}
			$kbps_index = self::get_kbps_index($media_info['nns_mode']);
			$media_hash = self::get_media_hash($media_info['nns_import_id'],$media_info['nns_cp_id']);
			$nns_cp_id = strlen($media_info['nns_cp_id']) < 1 ? 0 : $media_info['nns_cp_id'];
// 			$nns_media_type = (strlen($media_info['nns_filetype']) <1) ? 'ts' : 'hls';
// 			$flag_media_type = ($nns_media_type == 'hls' && $flag_media_type == 'hls') ? 'hls' : 'ts';
			
			$flag_media_type = $nns_media_type = (strlen($media_info['nns_filetype']) <1) ? 'ts' : ((strtolower($media_info['nns_filetype']) == 'm3u8') ? 'hls' : $media_info['nns_filetype']);
			//修复BUG，开启了DRM加密，当片源需要加密时才切片加密，不需要则不加密
			$drm_flag_enabled = $clip_flag_enabled ? (isset($media_info['nns_drm_enabled']) ? $media_info['nns_drm_enabled'] : $media_info['nns_drm_flag']) : 0;
			
			$drm_encrypt_way = '';
			if($drm_flag_enabled !=0)
			{
			    $cp_config = nl_cp::query_by_id_by_db($db, $media_info['nns_cp_id']);
			    if($cp_config['ret'] !=0)
			    {
			        return false;
			    }
			    $cp_config = (isset($cp_config['data_info']['nns_config']) && !empty($cp_config['data_info']['nns_config'])) ? json_decode($cp_config['data_info']['nns_config'],true) : null;
			    $cp_config = is_array($cp_config) ? $cp_config : null;
			    if(!isset($cp_config['main_drm_enabled']) || $cp_config['main_drm_enabled'] != 1)
			    {
			        $drm_flag_enabled=0;
			    }
			    else
			    {
			        if (isset($cp_config['q_disabled_drm']) && $cp_config['q_disabled_drm'] == 1)
			        {
			            $drm_encrypt_way='verimatrix';
			        }
			        else if (isset($cp_config['clip_drm_enabled']) && $cp_config['clip_drm_enabled'] == 1)
			        {
			            $drm_encrypt_way='taihe';
			        }
			        else if (isset($cp_config['q_marlin_drm_enable']) && $cp_config['q_marlin_drm_enable'] == 1)
			        {
			            $drm_encrypt_way='marlin';
			        }
			    }
			}

			$str_clip_custom_origin_id = (isset($cp_config['clip_custom_origin_id']) && strlen($cp_config['clip_custom_origin_id']) >0) ? $cp_config['clip_custom_origin_id'] : "";
			$str_media_temp_id = $media_info['nns_id'];
			$str_index_temp_id = $video_index_info['nns_import_id'];
			$media_cp_id = $media_info['nns_import_source'];
			if(isset($sp_config['clip_cp_id_sent_model']) && !empty($sp_config['clip_cp_id_sent_model']) && $sp_config['clip_cp_id_sent_model']=='1')
			{
 				$media_cp_id = $video_info['nns_producer'];
			}
			else if(isset($sp_config['clip_cp_id_sent_model']) && !empty($sp_config['clip_cp_id_sent_model']) && $sp_config['clip_cp_id_sent_model']=='2')
			{
			    $media_cp_id = $video_info['nns_cp_id'];
			}
			if((int)$sp_config['import_id_mode'] !== 1 && (int)$sp_config['import_id_mode'] !== 3)
			{
				$result_media_data = public_model_exec::get_asset_id_by_sp_id($param['nns_org_id'], 'media', $media_info['nns_id'],$media_info,$sp_config);
				$str_index_temp_id = $str_media_temp_id = (isset($result_media_data['data_info']) && strlen($result_media_data['data_info']) >0) ? $result_media_data['data_info'] : $media_info['nns_id'];
			}
			
			$str_live_to_media_desc='';
    		if($param['nns_video_type']==0 && $media_info['nns_live_to_media'] == '1' && strlen($media_info['nns_ext_url'])>0 && self::is_json($media_info['nns_ext_url']))
    		{
    		    $arr_nns_ext_url = json_decode($media_info['nns_ext_url'],true);
    		    if(isset($arr_nns_ext_url['playbill_playurls']) && !empty($arr_nns_ext_url['playbill_playurls']) && is_array($arr_nns_ext_url['playbill_playurls']))
    		    {
    		        $str_live_to_media_desc=' voda_id="'.$arr_nns_ext_url['playbill_playurls']['nns_content_id']
                        .'" voda_start_time="'.$arr_nns_ext_url['playbill_playurls']['start_date'].' '.$arr_nns_ext_url['playbill_playurls']['start_time']
                        .'" voda_time_len="'.$arr_nns_ext_url['playbill_playurls']['duration'].'" timezone="' . $arr_nns_ext_url['playbill_playurls']['timezone'].'" ';
    		    }
    		}
    		$str_temp_domain = $media_info['nns_domain'];
    		$str_temp_cms_id = $media_info['nns_cp_id'];
    		//ott模式xml的domiain和cms_id置空
			if($media_info['nns_cp_id'] == 'yngd' || $media_info['nns_cp_id'] == 'avit' || $media_info['nns_cp_id'] == 'zhongguangchuanbo' || $media_info['nns_cp_id'] == 'jycm')
			{
			    $str_temp_domain = '';
			    $str_temp_cms_id = '';
			    //$media_cp_id = $media_info['nns_cp_id'];
			}
			/******如果上游传的是绝对路劲，那么只保留相对路劲 xinxin.deng 2018/7/30 14:04 start*****/
			if (stripos($media_info['nns_url'], 'ftp://') === true || stripos($media_info['nns_url'], 'http://') === true)
            {
                $nns_url = parse_url($media_info['nns_url']);
                $media_info['nns_url'] = $nns_url['path'];
            }
            /******如果上游传的是绝对路劲，那么只保留相对路劲 xinxin.deng 2018/7/30 14:04 end*****/

			if(stripos($media_info['nns_url'], '&') !== FALSE)
			{
			    $media_info['nns_url'] = urlencode($media_info['nns_url']);
			}
			if(isset($sp_config['cdn_import_media_mode'])&&(int)$sp_config['cdn_import_media_mode']===1){
					$media_xml .= '<media id="'.$str_media_temp_id.'" name="'.htmlspecialchars($media_info['nns_name'], ENT_QUOTES).'" file_id="'.$media_info['nns_import_id'].
					'" content_id="'.$str_index_temp_id.'" content_url="'.$media_info['nns_url'].'" kbps_index="0'.$kbps_index.'" kbps="'.$media_info['nns_kbps'].'" md5="'.
					$media_hash.'" drm_enabled="'.$drm_flag_enabled.'" drm_encrypt_way="'.$drm_encrypt_way.'" cp_id="'.$media_cp_id.'" media_type="'.
					$nns_media_type.'" domain="'.$str_temp_domain.'" cms_id="'.$str_temp_cms_id.'" custom_origin_id="'.$str_clip_custom_origin_id.'"'.$str_live_to_media_desc.'/>';
			}
			elseif(isset($sp_config['cdn_import_media_mode'])&&(int)$sp_config['cdn_import_media_mode']===2){
				if($media_info['nns_id']==$param['nns_video_media_id']){
					$media_xml .= '<media id="'.$str_media_temp_id.'" name="'.htmlspecialchars($media_info['nns_name'], ENT_QUOTES).'" file_id="'.$media_info['nns_import_id'].
					'" content_id="'.$str_index_temp_id.'" content_url="'.$media_info['nns_url'].'" kbps_index="0'.$kbps_index.'" kbps="'.$media_info['nns_kbps'].'" md5="'.
					$media_hash.'" drm_enabled="'.$drm_flag_enabled.'" drm_encrypt_way="'.$drm_encrypt_way.'" cp_id="'.$media_cp_id.'" media_type="'.
					$nns_media_type.'" domain="'.$str_temp_domain.'" cms_id="'.$str_temp_cms_id.'" custom_origin_id="'.$str_clip_custom_origin_id.'"'.$str_live_to_media_desc.'/>';
				}
			}
			else
			{
				if($media_info['nns_id']==$param['nns_video_media_id']){
					$media_xml .= '<media id="'.$str_media_temp_id.'" name="'.htmlspecialchars($media_info['nns_name'], ENT_QUOTES).'" file_id="'.$media_info['nns_import_id'].
					'" content_id="'.$str_index_temp_id.'" content_url="'.$media_info['nns_url'].'" kbps_index="0'.$kbps_index.'" kbps="'.$media_info['nns_kbps'].'" md5="'.
					$media_hash.'" drm_enabled="'.$drm_flag_enabled.'" drm_encrypt_way="'.$drm_encrypt_way.'" cp_id="'.$media_cp_id.'" media_type="'.
					$nns_media_type.'" domain="'.$str_temp_domain.'" cms_id="'.$str_temp_cms_id.'" custom_origin_id="'.$str_clip_custom_origin_id.'"'.$str_live_to_media_desc.'/>';
				}
			}
			$i++;
		}
		if($i==0){
			$sql = "update nns_mgtvbk_clip_task set nns_state='get_media_url_fail' where nns_id='".$param['nns_id']."'";
			//echo $sql;
			$result = nl_execute_by_db($sql,$db_w);
			return false;
		}
		$media_xml .= '</media_list>';
		if((int)$sp_config['import_id_mode'] !== 1 && (int)$sp_config['import_id_mode'] !== 3)
		{
			$result_index_data = public_model_exec::get_asset_id_by_sp_id($param['nns_org_id'], $index_info_type, $param['nns_video_index_id'],$video_index_info,$sp_config);
			$param['nns_video_index_id'] = (isset($result_index_data['data_info']) && strlen($result_index_data['data_info']) >0) ? $result_index_data['data_info'] : $param['nns_video_index_id'];
		}
		$ret_index  = '<index id="'.$param['nns_video_index_id'].'" index="'.$video_index_info['nns_index'].'" name="'.htmlspecialchars($video_index_info['nns_name'], ENT_QUOTES).'" media_type="'.$flag_media_type.'">';	
		
		$ret_xml .=$ret_index.$media_xml;
		$ret_xml .='</index>';
		$ret_xml .=	'</index_list>';
		$ret_xml .= '</video>';
		$ret_xml .= '</task>';
		//$ret_xml .= '<result ret="0" reason="ok" />';
		//$ret_xml .= '</nn_api>';
		return $ret_xml;
	}
	
	/**
	 * 判断是否是json
	 * @param unknown $string
	 * @return boolean
	 */
	static public function is_json($string)
	{
	    if(!is_string($string))
	    {
	        return false;
	    }
	    $string = strlen($string) <1 ? '' : trim($string);
	    if(strlen($string) <1)
	    {
	        return false;
	    }
	    json_decode($string);
	    return (json_last_error() == JSON_ERROR_NONE);
	}
	
	static public function _build_task_file_package_content($db,$param)
	{
        $sql = "select * from nns_file_package where nns_id='".$param['nns_video_id']."'";
        $video_info = nl_db_get_one($sql,$db);
        $sp_config = sp_model::get_sp_config($param['nns_org_id']);
        include_once dirname(dirname(__FILE__)).'/'.$param['nns_org_id'].'/define.php';
        $str_media_download_url  = (isset($sp_config['down_url']) && !empty($sp_config['down_url'])) ? $sp_config['down_url'] : '';
        if(strlen($str_media_download_url) <1)
        {
            return false;
        }
        $force = !empty($param['nns_force'])?'1':'0';
        $result_video_data = public_model_exec::get_asset_id_by_sp_id($param['nns_org_id'], 'file', $param['nns_id'],$video_info,$sp_config);
        $video_info['nns_file_id'] = $str_media_temp_id = (isset($result_video_data['data_info']) && strlen($result_video_data['data_info']) >0) ? $result_video_data['data_info'] : $param['nns_video_id'];
        
        $url = $str_media_download_url.'file_id='.$video_info['nns_import_id'].'&cp_id='.$video_info['nns_cp_id'];
        $result = file_get_contents($url);
        $ret_arr = json_decode($result, true);
        if($ret_arr['err']=='1'){
            $task_log = array(
                'nns_task_id' => $param['nns_id'],
                'nns_state'   => 'get_media_url_fail',
                'nns_desc'	=> $url.'======='.$result,
            );
            self::add_task_log($task_log);
            return false;
        }
        $media_cp_id = $video_info['nns_import_source'];
        if(isset($sp_config['clip_cp_id_sent_model']) && !empty($sp_config['clip_cp_id_sent_model']))
        {
            $media_cp_id = $video_info['nns_producer'];
        }

        $video_info['nns_url'] = isset($video_info['nns_file_url']) && !empty($video_info['nns_file_url']) ? $video_info['nns_file_url'] : $video_info['nns_service_url'];
	    $ret_xml  ='<task id="'.$param['nns_id'].'" force="'.$force.'" model="0" file_save_mode="'.$sp_config['upload_clip_to_ftp_enabled'].'" ftp_addr="'.$sp_config['upload_clip_to_ftp_url'].'">';
	    $ret_xml .=    '<video id="'.$param['nns_file_id'].'" name="'.htmlspecialchars($video_info['nns_name'], ENT_QUOTES).'" video_type="'.$param['nns_video_type'].'" pinyin="">';
	    $ret_xml .=        '<index_list>';
	    $ret_xml .=            '<media_list>';
	    $ret_xml .=                '<media id="'.$param['nns_file_id'].'" name="'.htmlspecialchars($param['nns_name'], ENT_QUOTES).'" file_id="'.$param['nns_import_id'].'" content_id="'.$param['nns_import_id'].'" content_url="'.$video_info['nns_url'].'" kbps_index="001" kbps="1314" md5="" drm_enabled="0" drm_encrypt_way="" cp_id="'.$media_cp_id.'" media_type="file" domain="'.$video_info['nns_domain'].'" cms_id="'.$video_info['nns_cp_id'].'"/>';
	    $ret_xml .=            '</media_list>';
	    $ret_xml .=        '</index_list>';
	    $ret_xml .=    '</video>';
	    $ret_xml .='</task>';
	    return $ret_xml;
	}
	
	
	/**
	 * 删除任务
	 */
	static public function delete_task($task_id){
		return true;
		//$db = nn_get_db(NL_DB_WRITE);

		//$sql = "delete from nns_mgtvbk_clip_task where nns_id='$task_id'";
		//return nl_execute_by_db($sql,$db);
	}
	/**
	 * 取切片任务
	 *  取优先级权重高的任务
	 */
	static public function get_task($sp_id)
	{
		$db = nn_get_db(NL_DB_READ);
		$db_w = nn_get_db(NL_DB_WRITE);
		//查询切片是否已经关闭
		$sp_config = sp_model::get_sp_config($sp_id);
		if(isset($sp_config['disabled_clip'])&&(int)$sp_config['disabled_clip']===1){
			return false;
		}
		//默认drm不加密
		$clip_flag_enabled = (isset($sp_config['main_drm_enabled']) && (int)$sp_config['main_drm_enabled'] == 1) ? 1 : 0;
		$sql = "select * from nns_mgtvbk_clip_task where (ISNULL(nns_state) or nns_state='' or nns_state='add' or nns_state='live_to_media_wait') and nns_org_id='{$sp_id}' order by nns_priority desc,nns_create_time asc limit 1";

		$task_info =  nl_db_get_one($sql,$db);
		if($task_info == false) return false;
		
		if($task_info['nns_video_type'] == 2)
		{
		    $xml = self::_build_task_file_package_content($db,$task_info);
		}
		else
		{
    		$b_media_exists = self::_vod_media_exists_v2($task_info,$db);
    		if(!isset($b_media_exists[0]) || !is_array($b_media_exists[0]) || empty($b_media_exists[0]))
    		{
    			//该分集下还没有片源
    			DEBUG && i_write_log_core('分集下还没有片源'.var_export($task_info,true));
    			$sql = "update nns_mgtvbk_clip_task set nns_state='cancel' where nns_id='".$task_info['nns_id']."'";
    			nl_execute_by_db($sql,$db_w);
    			return false;
    		}
    		$b_media_exists = $b_media_exists[0];
    		$cp_config = nl_cp::query_by_id_by_db($db, $b_media_exists['nns_cp_id']);
    		if($cp_config['ret'] !=0)
    		{
    		    return false;
    		}
    		$cp_config = (isset($cp_config['data_info']['nns_config']) && !empty($cp_config['data_info']['nns_config'])) ? json_decode($cp_config['data_info']['nns_config'],true) : null;
    		$cp_config = is_array($cp_config) ? $cp_config : null;
    		if($clip_flag_enabled === 0)
    		{
    		    $clip_flag_enabled = (isset($cp_config['main_drm_enabled']) && (int)$cp_config['main_drm_enabled'] == 1) ? 1 : 0;
    		}
    		$xml  =self:: _build_task_content($task_info,$clip_flag_enabled,$cp_config);
		}
		if($xml===false)
		{
			return false;
		}
		$task_info['nns_content'] = $xml;
		$nns_content = htmlspecialchars($task_info['nns_content'], ENT_QUOTES);
		$sql = "update nns_mgtvbk_clip_task set nns_content='".$nns_content."' where nns_id='".$task_info['nns_id']."'";
		$result = nl_execute_by_db($sql,$db_w);
		//print_r($task_info);
		return $task_info;
	}
	
	/**
	 * 获取文件包xml
	 * @param unknown $task_info
	 * @param unknown $db
	 * @param unknown $db_w
	 * @return boolean|unknown
	 */
	static public function get_file_package($task_info,$db,$db_w)
	{
	    $b_media_exists = self::_file_package_exists($task_info,$db);
	    //var_dump($b_media_exists);die;
	    if(!isset($b_media_exists[0]) || !is_array($b_media_exists[0]) || empty($b_media_exists[0])){
	        //该分集下还没有片源
	        DEBUG && i_write_log_core('分集下还没有片源'.var_export($task_info,true));
	        $sql = "update nns_mgtvbk_clip_task set nns_state='cancel' where nns_id='".$task_info['nns_id']."'";
	        nl_execute_by_db($sql,$db_w);
	        return false;
	    }
	    $b_media_exists = $b_media_exists[0];
	    
	    
	    $xml  =self:: _build_task_content($task_info,0);
	    if($xml===false){
	        return false;
	    }
	    $task_info['nns_content'] = $xml;
	    $nns_content = htmlspecialchars($task_info['nns_content'], ENT_QUOTES);
	    $sql = "update nns_mgtvbk_clip_task set nns_content='".$nns_content."' where nns_id='".$task_info['nns_id']."'";
	    $result = nl_execute_by_db($sql,$db_w);
	    return $task_info;
	}
	
	static public function get_task_test($id){
		$db = nn_get_db(NL_DB_READ);
		
		$db_w = nn_get_db(NL_DB_WRITE);

		//and (ISNULL(nns_state) or nns_state='')
		$sql = "select * from nns_mgtvbk_clip_task " .
				"where  (ISNULL(nns_state) or nns_state='')  and nns_id='$id'" .
				"order by nns_priority desc,nns_create_time asc limit 1";
		
		$task_info =  nl_db_get_one($sql,$db);
		if($task_info == false) return false;
		$b_media_exists = self::_vod_media_exists($task_info);
		if(!$b_media_exists){
			//该分集下还没有片源
			DEBUG && i_write_log_core('分集下还没有片源'.var_export($task_info,true));
			$sql = "update nns_mgtvbk_clip_task set nns_state='cancel' where nns_id='".$task_info['nns_id']."'";
			//nl_execute_by_db($sql,$db_w);
			return false;
		}

		$task_info['nns_content'] = self:: _build_task_content($task_info);
		$sql = "update nns_mgtvbk_clip_task set nns_content='".$task_info['nns_content']."' where nns_id='".$task_info['nns_id']."'";
		//$result = nl_execute_by_db($sql,$db_w);
		return $task_info;
	}
	/**
	 * 取任务下片源
	 */
	static public function get_vod_media($task_info){
		$db = nn_get_db(NL_DB_READ);

		$sql = "select * " .
				" from nns_vod_media" .
				" where " .
				"  nns_vod_id='".$task_info['nns_video_id']."' " .
				" and nns_vod_index_id='".$task_info['nns_video_index_id']."'  and nns_deleted != 1 order by nns_kbps desc";
		return nl_db_get_all($sql,$db);
	}
	static public function get_live_media($task_info){
		$db = nn_get_db(NL_DB_READ);

		$sql = "select * " .
				" from nns_live_media" .
				" where " .
				"  nns_live_id='".$task_info['nns_video_id']."' " .
				" and nns_live_index_id='".$task_info['nns_video_index_id']."'";
		return nl_db_get_all($sql,$db);
	}	
	/**
	 * @$params array('nns_video_id','nns_video_type','nns_video_index_id','nns_media_id')
	 */
	static public function get_media_info($params){
		$db = nn_get_db(NL_DB_READ);
	
		$media_info = null;
		if($params['nns_video_type']==0){
			//vod
			$sql = "select * from nns_vod_media where nns_id='".$params['nns_media_id']."'";
			$media_info= nl_db_get_one($sql,$db);
		}else{
			//live
			$sql = "select * from nns_live_media where nns_id='".$params['nns_media_id']."'";
			$media_info= nl_db_get_one($sql,$db);
		}
		return $media_info;
	}
	/**
	 * 如果删除分集，则取消该分集的任务
	 * @param nns_vod_index_id
	 * 
	 */
	static public function cancel_task_by_vod_index($nns_vod_index_id){
		DEBUG && i_write_log_core('删除分集，取消之前未处理任务'."\n vod_index_id:".$nns_vod_index_id);
		$db = nn_get_db(NL_DB_READ);
	
		//
		$sql = "select * from nns_mgtvbk_clip_task where  nns_video_type='0' and nns_video_index_id='".$nns_vod_index_id."'";
		$result = nl_db_get_all($sql,$db);
		if($result == false){
			return false;
		}
		foreach($result as $task_item){
				$result = self::update_task($task_item['nns_id'],array('nns_state'=>self::TASK_C_STATE_CANCEL,'nns_desc'=>self::$task_state_arr[self::TASK_C_STATE_CANCEL]));
				if($result!= false){
					//nns_task_id,nns_state,nns_desc
					$task_log = array(
					'nns_task_id'=>$task_item['nns_id'],
					'nns_state' => self::TASK_C_STATE_CANCEL,
					'nns_desc'  => self::$task_state_arr[self::TASK_C_STATE_CANCEL],
					);
					self::add_task_log($task_log);					
				}else{
					DEBUG && i_write_log_core('删除分集时，取消之前未处理任务执行失败');
				}			
		}
		DEBUG && i_write_log_core('取消之前未处理任务ok');
		return true;
	}
	static public function get_task_by_id($task_id){
		$db = nn_get_db(NL_DB_READ);
		
		$sql = "select * from nns_mgtvbk_clip_task where nns_id='$task_id' ";
		return nl_db_get_one($sql,$db);
	}
	static public function get_task_vod_info($task_id){
		$db = nn_get_db(NL_DB_READ);
			
		$sql="select  vod_index.nns_name as index_name,vod_index.nns_index as nns_index,vod.nns_name as vod_name,vod.nns_pinyin,task.* " .
				"from nns_mgtvbk_clip_task task inner join nns_vod vod on (
 task.nns_video_id=vod.nns_id
)  inner join nns_vod_index vod_index on (
 vod_index.nns_id=task.nns_video_index_id
) where  task.nns_id='$task_id'  " ;
		return nl_db_get_one($sql,$db);

	}
	/**
	 * 更新任务状态
	 * @param $state 0:任务完成 
	 */
	static public function update_task($task_id,$info){
		$db = nn_get_db(NL_DB_WRITE);		
		return nl_db_update($db,'nns_mgtvbk_clip_task',$info,"nns_id='".$task_id."'");
	}
	/**
	 * 添加到任务log
	 * $task_log array(nns_task_id,nns_state,nns_desc)
	 */
	static public function add_task_log($task_log){
		$db = nn_get_db(NL_DB_WRITE);
		$task_info = self::get_task_by_id($task_log['nns_task_id']);
		$task_log['nns_id'] = np_guid_rand();
		$task_log['nns_video_type'] = $task_info['nns_video_type'];
		$task_log['nns_video_id'] = $task_info['nns_video_id'];
		$task_log['nns_video_index_id'] = $task_info['nns_video_index_id'];
		$task_log['nns_create_time'] = date('Y-m-d H:i:s');
		$task_log['nns_create_mic_time'] = microtime(true)*10000;
		return nl_db_insert($db,'nns_mgtvbk_clip_task_log',$task_log);
	}
	static public function get_task_detail_log($task_id){
		$db = nn_get_db(NL_DB_READ);
	   
		$sql = "select * from nns_mgtvbk_clip_task_log where nns_task_id='$task_id' order by nns_create_time desc,nns_create_mic_time desc";
		return nl_db_get_all($sql,$db);
	}
	/*
	 * 取任务列表
	 * @param $filter array查询条件
	 * @return array('data'=>查询结果集,'rows'=>总记录数)
	 */
	static public function get_task_list($sp_id,$filter,$start=0,$size=100){
		$db = nn_get_db(NL_DB_READ);
	 
		$wh = '';		
		if(!empty($filter['nns_task_name'])){
			$wh .= " and (task.nns_task_name like '%".$filter['nns_task_name']."%' ) ";
		}
		if(!empty($filter['nns_state'])){
			if($filter['nns_state']=='wait'){
				$wh .= " and (task.nns_state='' or task.nns_state is null) ";
			}else{
				$wh .= " and task.nns_state='".$filter['nns_state']."'";
			}
		   
		}


		if(!empty($filter['nns_file_hit'])){
			$wh .= " and (task.nns_file_hit='".$filter['nns_file_hit']."' ) ";
		}
		
		if(!empty($filter['day_picker_start'])){
			$wh .= " and task.nns_create_time>='".$filter['day_picker_start']."'";
		}
		if(!empty($filter['day_picker_end'])){
			$wh .= " and task.nns_create_time<='".$filter['day_picker_end']."'";
		}
		
		if(!empty($filter['day_picker_put_start'])){
			$wh .= " and task.nns_alive_time>='".$filter['day_picker_put_start']."'";
		}
		if(!empty($filter['day_picker_put_end'])){
			$wh .= " and task.nns_alive_time<='".$filter['day_picker_put_end']."'";
		}
		if(strlen($filter['nns_video_type']) >0)
		{
		    $wh .= " and task.nns_video_type='".$filter['nns_video_type']."'";
		}
		
		if(!empty($filter['start_time'])){
			$wh .= " and task.nns_start_time>='".$filter['start_time']."'";
		}
		if(!empty($filter['end_time'])){
			$wh .= " and task.nns_end_time<='".$filter['end_time']."'";
		}
		
		if(!empty($filter['nns_id'])){
			$wh .= " and task.nns_id='".$filter['nns_id']."'";
		}
		if(isset($filter['nns_cp_id']) && strlen($filter['nns_cp_id']) >0){
		    $wh .= " and task.nns_cp_id='".$filter['nns_cp_id']."'";
		}

        if(isset($filter['nns_tom3u8_id']) && strlen($filter['nns_tom3u8_id']) >0){
            $wh .= " and task.nns_tom3u8_id='".$filter['nns_tom3u8_id']."'";
        }
		
		$sql="select  task.* " .
				"from nns_mgtvbk_clip_task task  where task.nns_org_id='$sp_id' and  (task.nns_state!='cancel' or ISNULL(task.nns_state) or task.nns_state='') " .$wh;
		$sql .= " order by task.nns_priority desc,task.nns_create_time desc ";
		$sql .= "limit $start,$size";
		$data =  nl_db_get_all($sql,$db);
		$count_sql="select  count(*) " .
				"from nns_mgtvbk_clip_task task  where task.nns_org_id='$sp_id' and (task.nns_state!='cancel' or ISNULL(task.nns_state) or task.nns_state='') " .$wh;
		$rows = nl_db_get_col($count_sql,$db);
		
		return array('data'=>$data,'rows'=>$rows);
	}



	static public function  get_delete_task($sp_id,$filter,$start=0,$size=100){
		$db = nn_get_db(NL_DB_READ);
		
		$wh = '';		
		if(!empty($filter['nns_task_name'])){
			$wh .= " and (a.nns_task_name like '%".$filter['nns_task_name']."%' ) ";
		}
		
		if(!empty($filter['nns_id'])){
			$wh .= " and a.nns_id='".$filter['nns_id']."'";
		}
		
		$sql = 'select count(a.nns_id) as num from nns_mgtvbk_clip_task a where  a.nns_org_id=\''.$sp_id.'\'   
'.$wh.' and 
   exists (
	select 1 from nns_vod_media b where b.nns_id=a.nns_video_media_id and b.nns_deleted=1
) ';
		$rows = nl_db_get_col($sql,$db);
		//echo $sql;
		unset($sql);
		$sql = 'select a.* from nns_mgtvbk_clip_task a where  a.nns_org_id=\''.$sp_id.'\'  
  '.$wh.' and 
   exists (
	select 1 from nns_vod_media b where b.nns_id=a.nns_video_media_id and b.nns_deleted=1
) ';
		$sql .= " order by a.nns_create_time desc limit $start,$size";
		$data =  nl_db_get_all($sql,$db);
		unset($sql);
		return array('data'=>$data,'rows'=>$rows);
	}



	/**
	 * $priority up:增加优先级 down：减少优先级权重 top:最高999 bottom:最低0
	 * 设置任务优先级 9999为最高 0为最低
	 */
	static public function set_task_priority($task_id,$priority='top'){
		$db_w = nn_get_db(NL_DB_WRITE);
	 	/*
		if($priority == 'top'){
			$sql = "update nns_mgtvbk_clip_task SET nns_priority=9999 where nns_id='$task_id'";
			return nl_execute_by_db($sql,$db_w);
		}
		if($priority == 'bottom'){
			$sql = "update nns_mgtvbk_clip_task SET nns_priority=0 where nns_id='$task_id'";
			return nl_execute_by_db($sql,$db_w);
		}*/
				

		$sql = null;
		switch($priority){
			case 'top':
			$sql = "update nns_mgtvbk_clip_task SET nns_priority=9999 where nns_id='$task_id'";
			break;
			case 'up':
			$sql = "update nns_mgtvbk_clip_task SET nns_priority=LEAST(9999,nns_priority+1) where nns_id='$task_id'";
			break;
			case 'down':
			$sql = "update nns_mgtvbk_clip_task SET nns_priority=GREATEST(0,nns_priority-1) where nns_id='$task_id'";
			break;
			case 'bottom':
			$sql = "update nns_mgtvbk_clip_task SET nns_priority=0 where nns_id='$task_id'";
			break;						
		}
		if($sql != null){
			return nl_execute_by_db($sql,$db_w);
		}
		return false;
	}
	/**
	 * 批量设置权重
	 * @param string $str_weight_ids nns_mgtvbk_clip_task中的 guid
	 * @param string $sp_id 运营商id
	 * @return boolean|number true 成功 | false 失败 | 9999 权重超过上限
	 * @author liangpan
	 * @date 2015-07-01
	 */
	static public function set_weight($str_weight_ids,$sp_id)
	{
		$str_weight_ids=trim($str_weight_ids,',');
		$arr_weight_ids=explode(',', $str_weight_ids);
		$arr_weight_ids=array_filter($arr_weight_ids);
		if(empty($arr_weight_ids))
		{
			return true;
		}
		$db_w = nn_get_db(NL_DB_WRITE);
		$db_r = nn_get_db(NL_DB_READ);
		$sql_query="select nns_priority from nns_mgtvbk_clip_task where nns_priority < 9999 and " . 
			" (ISNULL(nns_state) or nns_state='' or nns_state='add')  and nns_org_id='{$sp_id}' order by nns_priority desc limit 1";
		$result_query=nl_query_by_db($sql_query, $db_r);
		if(!$result_query || !isset($result_query[0]['nns_priority']))
		{
			return false;
		}
		$num = (int)$result_query[0]['nns_priority'];
		foreach ($arr_weight_ids as $val)
		{
			$num++;
			if($num >= 9999)
			{
				return 9999;
			}
			$sql_update="update nns_mgtvbk_clip_task set nns_priority='{$num}' where nns_id='{$val}' and " . 
			" (ISNULL(nns_state) or nns_state='' or nns_state='add')  and nns_org_id='{$sp_id}'";
			$result_update = nl_execute_by_db($sql_update, $db_w);
			if(!$result_update)
			{
				return false;
			}
		}
		return true;
	}
	
	/**
	 * 批量取消权重
	 * @param string $str_weight_ids nns_mgtvbk_clip_task中的 guid
	 * @param string $sp_id 运营商id
	 * @return boolean  true 成功 | false 失败
	 * @author liangpan
	 * @date 2015-07-01
	 */
	static public function cancel_weight($str_weight_ids,$sp_id)
	{
		$str_weight_ids=trim($str_weight_ids,',');
		$arr_weight_ids=explode(',', $str_weight_ids);
		$arr_weight_ids=array_filter($arr_weight_ids);
		if(empty($arr_weight_ids))
		{
			return true;
		}
		$db_w = nn_get_db(NL_DB_WRITE);
		$str_weight_ids = implode("','", $arr_weight_ids);
		$sql_update="update nns_mgtvbk_clip_task set nns_priority='0' where nns_org_id='{$sp_id}' and nns_id in('{$str_weight_ids}')";
		$result_update = nl_execute_by_db($sql_update, $db_w);
		return $result_update ? true : false;
	}
	
	/**
	 * 是否可以删除切片
	*/
	static public function can_delete_clip_file($task_id){
		$db = nn_get_db(NL_DB_READ);
		 $sql = "SELECT * FROM `nns_mgtvbk_clip_task` where `nns_id`='".$task_id."'";
		 $result = nl_db_get_one($sql,$db);
		 if(empty($result)){
			return true;
		 }	   
		 if(is_array($result)&&$result!=null){
			$sql_op = "SELECT * FROM `nns_mgtvbk_op_queue` where `nns_id`='".$result['nns_op_id']."'";
			$result_op = nl_db_get_one($sql_op,$db);
			if(empty($result_op)){
				return true;
			}
			
			if(is_array($result_op)&&$result_op!=null){
				return false;
			}
						
		}	
		return true; 
	}
	
	
	/**
	 * 是否可以删除切片
	 */
	static public function can_delete_clip_file_new($task_id){
		//return false;
		 $db = nn_get_db(NL_DB_READ);
		 $sql = "SELECT * FROM `nns_mgtvbk_clip_task` where `nns_id`='".$task_id."'";
		 $result = nl_db_get_one($sql,$db);
		 if(empty($result)){
		 	return true;
		 }		 
		 if(is_array($result)&&$result!=null){
		 	$sql_op = "SELECT * FROM `nns_mgtvbk_op_queue` where `nns_id`='".$result['nns_op_id']."'";
		 	$result_op = nl_db_get_one($sql_op,$db);
			if(empty($result_op)){
				return true;
			}
			
			if(is_array($result_op)&&$result_op!=null){
				return false;
			}
		 				
		}	 
		return true;
	}
	
	static public function movie_c2_execute(){
		$db = nn_get_db(NL_DB_READ);
		$db_w = nn_get_db(NL_DB_WRITE);
		 
		$sql =  "select clip.nns_id as nns_id from nns_mgtvbk_clip_task as clip,nns_mgtvbk_c2_task c2 where clip.nns_video_index_id=c2.nns_ref_id and c2.nns_type='index' and c2.nns_status=0 and clip.nns_state='ok' and c2.nns_org_id='fjyd' and clip.nns_org_id='fjyd'  order by clip.nns_modify_time desc limit 30";
		$task_arr = nl_db_get_all($sql,$db);
		if(is_array($task_arr)){
			foreach($task_arr as $task_item){
				//
				$rs = c2_task_model::add_movies_by_clip_task($task_item['nns_id']);
				if($rs){	
					nl_execute_by_db("update nns_mgtvbk_clip_task set nns_state='c2_handle' where nns_id='".$task_item['nns_id']."'",$db_w);
				}					
			}
		}
	}
	static public function resend_movie_c2_execute(){
		$db = nn_get_db(NL_DB_READ);
		$db_w = nn_get_db(NL_DB_WRITE);
		 
		$sql =  "select clip.nns_id as nns_id from nns_mgtvbk_clip_task as clip,nns_mgtvbk_c2_task c2 where clip.nns_video_index_id=c2.nns_ref_id and c2.nns_type='index' and c2.nns_status=0 and clip.nns_state='c2_fail' and c2.nns_org_id='fjyd' and clip.nns_org_id='fjyd'  order by clip.nns_modify_time desc limit 100";
		$task_arr = nl_db_get_all($sql,$db);
		if(is_array($task_arr)){
			foreach($task_arr as $task_item){
				//
				$rs = c2_task_model::add_movies_by_clip_task($task_item['nns_id']);
				if($rs){	
					nl_execute_by_db("update nns_mgtvbk_clip_task set nns_state='c2_handle' where nns_id='".$task_item['nns_id']."'",$db_w);
				}					
			}
		}
	}
	static public function delete_movie_by_task_id($task_ids,$bool=false){
		$db = nn_get_db(NL_DB_WRITE);
		$ids = array();
		if(is_array($task_ids)){
			$ids = $task_ids;
		}else if(is_string($task_ids)){
			$ids[] = $task_ids;
		}
		if(empty($ids)) return ;
		foreach($ids as $id){
			$task_info = self::get_task_by_id($id);
			nl_execute_by_db("delete from nns_mgtvbk_clip_task where nns_id='$id'", $db);
			if($bool){
				nl_execute_by_db("delete from nns_mgtvbk_op_queue where nns_id='{$task_info['nns_op_id']}'", $db);
				nl_execute_by_db("delete from nns_mgtvbk_op_queue where nns_org_id='{$task_info['nns_org_id']}' and nns_type='media' and nns_action!='destroy' and nns_media_id='{$task_info['nns_video_media_id']}'", $db);				
				$update_c2_task = "update nns_mgtvbk_c2_task set nns_status=7,nns_epg_status=100 where nns_org_id='{$task_info['nns_org_id']}' and nns_type='media' and nns_ref_id='{$task_info['nns_video_media_id']}'";
				nl_execute_by_db($update_c2_task, $db);
			}
		}
		return true;
	}
	//通过任务列表添加新的切片任务
	static public function add_task_movie_clip($query){
		$db = nn_get_db(NL_DB_READ);
		$db_w = nn_get_db(NL_DB_WRITE);				
		//条件：有新片源，并且分分片信息已经注入,并且MEDIA_TIME_OUT 秒 没有片源更新;每次限制跑30条		
		$vod_index_id = $_GET['nns_vod_index_id'];
		$where = "";
		if(!empty($vod_index_id)){
			$where = " and nns_id='".$vod_index_id."'";
		}
		$sql = "select * from nns_vod_index where nns_deleted != 1 and nns_vod_id='".$query['nns_vod_id']."' ".$where;
		$indexes = nl_db_get_all($sql,$db);
		if(is_array($indexes) && count($indexes)>0){
			foreach($indexes as $index_info){
				$task_info['nns_video_type'] = 0;
				$task_info['nns_video_id'] = $index_info['nns_vod_id'];
				$task_info['nns_video_index_id'] = $index_info['nns_id'];
				$task_info['nns_index'] = $index_info['nns_index'];
				$sql_clip = "select * from nns_mgtvbk_clip_task where nns_org_id='fjyd' and nns_video_id='{$index_info['nns_vod_id']}' and nns_video_index_id='{$index_info['nns_id']}'";
				$clip_task = nl_db_get_one($sql_clip, $db);
				if(is_array($clip_task)&&$clip_task!=null){
					if($clip_task['nns_state']!='c2_ok'){						
						nl_execute_by_db("update nns_mgtvbk_clip_task set nns_state=null,nns_content=null,nns_force=0 where nns_id='{$clip_task['nns_id']}'", $db_w);
					}					
				}else{
					self::add_task($task_info);
				}				
				// $sql_c2_index = "select * from nns_mgtvbk_c2_task where nns_org_id='fjyd' and nns_tpye='index' and nns_ref_id='{$index_info['nns_id']}'";
				// $c2_task = nl_db_get_one($sql_c2_index, $db);
				// if(is_array($c2_task)&&$c2_task!=null){
					// nl_execute_by_db("update nns_mgtvbk_c2_task set nns_status=0,nns_action='add'  where nns_id='{$c2_task['nns_id']}'", $db_w);
				// }else{						
					// $data = array(
						// 'nns_id'=>np_guid_rand('fjyd'),
						// 'nns_type'=>'index',
						// 'nns_name'=>$index_info['nns_name'],
						// 'nns_ref_id'=>$index_info['nns_id'],
						// 'nns_org_id'=>'fjyd',
						// 'nns_action'=>'add',
						// 'nns_status'=>1,
						// 'nns_create_time'=>date('Y-m-d H:i:s'),
						// 'nns_src_id'=>$index_info['nns_vod_id'],
					// );
					// $re = nl_db_insert($db_w, 'nns_mgtvbk_c2_task', $data);
				// }		
			}
		}else{
			DEBUG && i_write_log_core('没有有新片源的分集');
		}		
		return true;
	}
	/**
	 * 通过切片任务ID批量获取片源、分集、主媒资注入ID
	 * @param array $task_id 任务ID组  array($task_id,$task_id)
	 * @return array
	 * @date 2016-04-01
	 * @author zhiyong.luo
	 */
	static public function get_import_id_by_task_id($dc,$task_id,$sp_id)
	{
		if(!is_array($task_id) || empty($task_id))
		{
			return false;
		}
		$sql = "select c.nns_id,v.nns_cp_id,v.nns_asset_import_id as video_import_id,v.nns_name,
			i.nns_import_id as index_import_id,m.nns_import_id as media_import_id,m.nns_cp_id as media_cp_id  
			from nns_mgtvbk_clip_task as c,nns_vod as v,nns_vod_index as i,nns_vod_media as m 
			where c.nns_video_id=v.nns_id and c.nns_video_index_id=i.nns_id and 
			c.nns_video_media_id=m.nns_id and v.nns_deleted!=1 and i.nns_deleted!=1 and m.nns_deleted!=1 ";
		$task_id_strs = implode("','", $task_id);
		$sql .= "and c.nns_id in ('{$task_id_strs}') and c.nns_org_id='{$sp_id}'";
		return nl_query_by_db($sql, $dc->db());
	}
}
